import os, sys, copy

parent_path = os.path.abspath(os.path.join(__file__, *([".."] * 5)))
sys.path.insert(0, parent_path)

import traceback, requests, threading
import numpy as np
import time
import socket, json, cv2, yaml
from typing import *
from core.task.modules.processors.base_processor import BaseProcessor
from core.utils.logger import logging


class VideoTranscode(BaseProcessor):
    def __init__(
        self,
        keys,
        VideoTranscode_remove_in,
    ) -> None:
        """
        keys:
            in: 输入视频地址
            out: 输出视频地址
        VideoTranscode_remove_in: 是否删除输入视频
        """
        self.keys = keys
        self.remove_in = VideoTranscode_remove_in

    def _init_check(self):
        assert "in" in self.keys
        assert not self.remove_in is None

    def _set(self, data: Dict):
        if data.get("remove_in", False):
            self.remove_in = data["remove_in"]

    def _call(self, data: Dict) -> Dict:
        if data.get(self.keys["in"], False):
            video_in_path = data.pop(self.keys["in"])
            video_out_path = data.pop(self.keys["out"])
            cmd = "ffmpeg -i {} -y -vcodec h264 -b:v 0 -s 1920x1080 {}".format(
                video_in_path, video_out_path
            )
            logging.info(cmd)
            os.system(cmd)
            # 转码后删除老文件
            if video_in_path != video_out_path and self.remove_in:
                logging.info(f"删除文件 : {video_in_path}")
                os.remove(video_in_path)
        return data

    def start(self):
        return super().start()


if __name__ == "__main__":
    video_transcode_key = {
        "keys": {"in": "video_in_path", "out": "video_out_path"},
        "remove_in": False,
    }
    video_transcode = VideoTranscode(**video_transcode_key)
    # video_transcode.set({"remove_in": True})
    video_transcode.start()
    data = {
        "video_in_path": "/home/smartgis/workspace/project/smart_server/output/temp.mp4",
        "video_out_path": "/home/smartgis/workspace/project/smart_server/output/temp1.mp4",
    }
    video_transcode(data)
    video_transcode.close()
